package cn.dengl.sky.springboot.common.config.security;

import cn.dengl.sky.springboot.sys.dao.UserDao;
import cn.dengl.sky.springboot.sys.entity.User;
import cn.dengl.sky.springboot.sys.entity.UserRole;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;

public class CustomUserService implements UserDetailsService {
    @Inject
    private UserDao userDao;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user=userDao.findByLogin(username);
        //System.out.println("user"+user.toString());
        if(user==null){
            throw new  UsernameNotFoundException("用户名不存在");
        }
        //自定义错误的文章说明的地址：http://blog.csdn.net/z69183787/article/details/21190639?locationNum=1&fps=1
        if(user.getState().equalsIgnoreCase("0")){
            throw new LockedException("用户账号被冻结，无法登陆请联系管理员！");
        }
//        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
//        //加用户的权限。只要把用户权限添加到authorities 就万事大吉。
//        for(UserRole role:user.getRoles())
//        {
//            authorities.add(new SimpleGrantedAuthority(role.getName()));
//            System.out.println(role.getName());
//        }
//        return  new org.springframework.security.core.userdetails.User(user.getUserName(), user.getPassword(), authorities);
        return user;
    }
}
